package com.apes.scm.sal.saleOrder;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.LogicalUtil;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.contract.model.Contract;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.service.UomService;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import java.util.Map;

/**
 * 功能：分销订单明细
 *
 * @author xul
 * @create 2018-01-25 19:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = SaleOrderItem.CONST_TABLE_NAME)
public class SaleOrderItem extends BaseModel {
    public static final String CONST_TABLE_NAME = "sale_order_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "分销订单明细")
    private String id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier;

    @ManyToOne(optional = false)
    @JoinColumn(name = "sale_id", referencedColumnName = "id", nullable = false)
    @Comment("订单")
    private SaleOrder saleOrder;

    @Column(name = "remark", length = 120)
    @Comment("备注")
    private String remark;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id", nullable = false)
    @Comment("商品")
    private Product product;

    @Column(name = "price_subtotal", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("小计（未含税金额）")
    private double priceSubtotal = 0;

    @Column(name = "price_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double priceTax = 0;

    @Column(name = "discount", nullable = false, columnDefinition = ApesConst.FIELD_16_4)
    @Comment("折扣（返利）金额")
    private double discount = 0;

    @Column(name = "price_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double priceTotal = 0;

    @Column(name = "price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("单价")
    private double priceUnit = 0;

    @Column(name = "cost_price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("成本单价")
    private double costPriceUnit = 0;       // 当存在跨工时采购、销售时，这里记录分销单找供应商采购的价格

    @Column(name = "price_limit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("限价")
    private double priceLimit = 0;

    @Column(name = "suggest_Price", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("建议价")
    private double suggestPrice = 0;

    @Column(name = "product_uom_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("数量")
    private double productUomQty = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id", nullable = false)
    @Comment("计量单位")
    private ProductUom uom;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tax_id", referencedColumnName = "id", nullable = false)
    @Comment("税率")
    private Tax tax;

    @Column(name = "qty_invoiced", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("开票数量")
    private double qtyInvoiced = 0;

    @Column(name = "qty_cancle", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("取消数量")
    private double qtyCancle = 0;

    @Column(name = "qty_received", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("交货数量")
    private double qtyDeliver = 0;

    @Column(name = "qty_returned", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("已退货数量")
    private double qtyReturned = 0;

    @Column(name = "qty_returning", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("退货中...")
    private double qtyReturning = 0;

    @Column(name = "qty_delivering", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("提单冲红数量")
    private double qtyDelivering = 0;

    @Column(name = "qty_delivered", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("退货冲红数量")
    private double qtyDelivered = 0;

    @Column(name = "oos", nullable = false, columnDefinition = "number(1,0) default 0")
    @Comment("无库存销售标记")
    private boolean oos = false; //无库存销售标记（OOS：out of stock）

    @Column(name = "qty_voucher", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("凭证数量")
    private double qtyVoucher = 0;      // 用于记录是否所有的商品都以写完凭证

    @Column(name = "originItemId")
    @Comment("来源行号")
    private String originItemId;  //来源行号


    @Column(name = "invoiced_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("已开票金额")
    private double invoicedAmount = 0;

    @Column(name = "invoice_number", length = 256)
    @Comment("发票号码")
    private String invoiceNumber;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "batch_code", referencedColumnName = "id")
    @Comment("商品批次内码")
    private InventoryBatch inventoryBatch; // 指定商品批次（带安/服务）

    @Comment("商品规则")
    @Column(name = "product_rule", columnDefinition = ApesConst.FIELD_QTY_16_4)
    private Integer productRule;//0  有库存商品  10  带安商品（代销）  20  带安商品（经销）  30  其他商品

    public void setProductRule(int productRule){
        this.productRule = productRule;
    }

    public int getProductRule(){
        if (productRule == null) {
            if (this.product.getProductGroup().checkWorkProduct()) return 30;
            if (this.product.getProductGroup().checkPartProduct()) return 0;
            if ("50".equals(this.product.getProductGroup().getId())) return 0;
        }
        return productRule;
    }

    @Column(name = "paint_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("油漆价格")
    private Double paintPrice; // 油漆销售价格

    @Column(name = "paint_purchase_Price", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("油漆采购价格")
    private Double paintPurchasePrice; // 油漆采购价格

    @Column(name = "paint_Flag", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE) // nullable = false,
    @Comment("油漆商品标记")
    private boolean paintFlag = false; // 油漆商品标记

    @Column(name = "paint_type", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("油漆类别(0:水性;1:油性)")
    private int paintType = 0;  // 油漆类别(0:水性;1:油性)

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "contract_id", referencedColumnName = "id")
    @Comment("外协采购合同")
    private Contract contract;

    @Column(name = "inner_sale_price_unit", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("内部销售单价")
    private double innerSalePriceUnit = 0;      // 外协代销带安找供应商采购价(非跨公司)

    @Column(name = "price_out_unit_in_tax", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("含税带安成本单价")
    private double priceOutUnitInTax = 0;  // 外协找车宝，车宝找供应商的采购价;

    @Transient
    private Double marketableQty;  // 获取实时库存

    public Double getMarketableQty() {
        if (!saleOrder.getState().equals("sent")) return null;
        ProductAccountService productAccountService = SpringManager.getBean(ProductAccountService.class);
        Map map = productAccountService.getUsableQtyToUom(saleOrder.getLocation(), product, uom, company);
        if (map.isEmpty()) return 0.00;
        return (Double) map.get("marketableQty") + productUomQty;
    }


    public void computeAmt() {
        Map result = this.computeTax().computeAll(this.getCompany(), priceUnit, productUomQty);
        priceTax = ((Double) result.get("taxAmt")).doubleValue();
        priceSubtotal = ((Double) result.get("totalExcluded")).doubleValue();
        priceTotal = ((Double) result.get("totalIncluded")).doubleValue();
    }

    /**
     * 功能：计算无税库存单价
     */
    public double computeExcludedPriceUnit() {
        double price = this.priceUnit;
        if (this.getTax() != null) {
            price = (double) this.getTax().computeAll(this.getSaleOrder().getCompany(), price, 1.0).get("totalExcluded");
        }
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /**
     * 功能：计算含税库存单价
     */
    public double computePriceUnit() {
        double price = this.priceUnit;
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /**
     * 功能：计算基本单位库存量
     */
    public double computeQtyUnit(double uomQty) {
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            return this.getUom().computeQty(uomQty, baseUom, true);
        }
        return uomQty;
    }

    private ProductUom getProductUom() {
        UomService uomService = SpringManager.getBean(UomService.class);
        return uomService.getUom(this.getCompany(), this.getProduct());
    }

    public Tax computeTax() {
        TaxService taxService = SpringManager.getBean(TaxService.class);
        tax = taxService.getSaleTax(saleOrder.getCompany(), product);
        return tax;
    }

    /**
     * 交货
     */
    public void delivery(double qtyDone) {
        this.qtyDeliver += qtyDone;
        // 当前可交货数量 = 销售数量 - 取消数量
        if (qtyDeliver > productUomQty - qtyCancle) {
            throw new RuntimeException("交货和取消数量之和不能大于销售数量，当前可交货数量：" + (productUomQty - qtyCancle));
        }
    }

    /**
     * 取消
     */
    public void cancle(double qtyDone) {
        this.qtyCancle += qtyDone;
        // 当前可取消数量 = 销售数量 - 交货数量
        if (qtyCancle > productUomQty - qtyDeliver) {
            throw new RuntimeException("交货和取消数量之和不能大于销售数量，当前可退数量：" + (productUomQty - qtyDeliver));
        }
    }

    /**
     * 合计退货中数量
     */
    public void sumQtyReturning(double qtyDelivering, double qtyDelivered){
        this.qtyDelivering += qtyDelivering;
        this.qtyDelivered += qtyDelivered;
        this.qtyReturning = this.qtyDelivering + this.qtyDelivered;
        if( (productUomQty - qtyReturned) <  qtyReturning) throw new RuntimeException("退货数量不能大于销售数量，当前可退货数量为：" + (productUomQty - qtyReturned));
    }


    /***
     * 退货在途 +  已退货 <= 销售数量
     */

    public void calcQtyReturned(double qtyReturned) {
        if ((this.qtyReturned + qtyReturned + this.qtyReturning) > productUomQty)
            throw new RuntimeException("退货在途数量和已退货数量之和不能大于可退货数量，当前可退数量：" + (productUomQty - this.qtyReturned - this.qtyReturning));
        this.qtyReturned += qtyReturned;
    }

    /**
     * 可提单冲红数量
     */

    @Transient
    private double qtyDeliveringLimit;

    public double getQtyDeliveringLimit() {
        if (getProductRule() == 0) {
            return productUomQty - qtyDeliver - qtyCancle - qtyDelivering;
        }else {
            if (LogicalUtil.in(product.getType(), "aut")) {
                return productUomQty - qtyDelivering - qtyCancle;
            } else {
                return -qtyCancle - qtyDelivering;
            }
        }
    }

    /**
     * 可退货冲红数量
     */
    @Transient
    private double qtyDeliveredLimit;

    public double getQtyDeliveredLimit(){
        if (getProductRule() == 0) {
            return qtyDeliver - (qtyReturned - qtyCancle) - qtyDelivered;
        }else {
            if (LogicalUtil.in(product.getType(), "aut")) {
                return 0;
            } else {
                return productUomQty - (qtyReturned - qtyCancle) - qtyDelivered;
            }
        }
    }

    // 计算可退货数量，LossSaleReturn 使用
    public double calcQtyDeliveredLimit(){
        return productUomQty - (qtyReturned - qtyCancle) - qtyDelivered;
    }
}
